﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Chaine.Models;
using Chaine.DAO;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace Chaine.DAO
{
    public class EmailTemplateManager
    {
        private static MongoCollection<EmailTemplateModels> _EmailTemplates;
        private static MongoCollection<EmailTemplateModels> EmailTemplates
        {
            get
            {
                if (_EmailTemplates != null)
                    return _EmailTemplates;
                _EmailTemplates = DAO.DB.GetDBInstance().GetCollection<EmailTemplateModels>("EmailTemplates");
                return _EmailTemplates;
            }
        }
        /// <summary>
        /// 获取所有的email模板
        /// </summary>
        /// <returns></returns>
        public static List<EmailTemplateModels> GetEmailTemplates()
        {
            var result = new List<EmailTemplateModels>() { 
                GetEmailTemplate(EmailTemplateType.AlertNewMember),
                GetEmailTemplate(EmailTemplateType.ResetPassword),
                GetEmailTemplate(EmailTemplateType.VerifyEmail)
            };
            return result;
        }

        public static EmailTemplateModels GetEmailTemplate(EmailTemplateType type)
        {
            var result = EmailTemplates.FindOne(Query.EQ("Type", type));
            if (result == null)
            {
                result = new EmailTemplateModels(type);
                EmailTemplates.Insert(result);
            }
            return result;
        }

        internal static object GetEmailTemplate(MongoDB.Bson.ObjectId objectId)
        {
            return EmailTemplates.FindOne(Query.EQ("_id", objectId));
        }

        internal static bool UpdateEmailTemplate(EmailTemplateModels email)
        {
            return EmailTemplates.Save(email).Ok;
        }
    }
}